<?php

namespace App\Kuafu\WaiMai\Command;

use App\Kuafu\Base\Model\BaseModel;
use App\Kuafu\WaiMai\Enum\WaiMaiDBEnum;
use App\Kuafu\WaiMai\Model\WaiMaiCallbackLogModel;
use App\Kuafu\WaiMai\Model\WaiMaiOrderDetailModel;
use App\Kuafu\WaiMai\Model\WaiMaiOrderModel;
use App\Kuafu\WaiMai\Model\WaiMaiPartRefundLogModel;
use GuzzleHttp\Client;
use GuzzleHttp\RequestOptions;
use Illuminate\Console\Command;

class WaiMaiTestCallback extends Command
{
    /**
     * The name and signature of the console command.
     *
     * @var string
     */
    protected $signature = 'waimai:test-callback {shopId} {orderId?} {startDate?}';

    /**
     * The console command description.
     *
     * @var string
     */
    protected $description = '外卖订单-模拟回调';

    /**
     * Create a new command instance.
     *
     * @return void//
     */
    public function __construct()
    {
        parent::__construct();
    }

    /**
     * 数据校验的异常信息
     * @var array
     */
    private array $errs = [];

    /**
     * Execute the console command
     *
     * @return int
     */
    public function handle()
    {
        if (config('app.env') == 'prod' || config('app.env') == 'pre') {
            dd('生产环境不允许执行');
        }

        $startTime = time();

        ini_set('memory_limit', '-1');

        // Ymd类似格式
        $startDate = (string)$this->argument('startDate');
        $shopId    = (int)$this->argument('shopId');
        $orderId   = (int)$this->argument('orderId');

        $start = strtotime($startDate);
        $end   = $start + 86400 + 3600 * 4;

        dump("Start Date:" . date('Y-m-d', $start) . " ShopId:{$shopId} OrderId:{$orderId} Ready to Go:");
//        sleep(1);

        $bakShopId = $shopId;

        // 删数据
        WaiMaiOrderModel::suffix($shopId)
                        ->when($start, function ($query) use ($start, $end) {
                            $query->whereBetween('createdAt', [$start, $end]);
                        })
                        ->when($orderId, function ($query) use ($orderId) {
                            $query->where('orderId', $orderId);
                        })
                        ->where('shopId', $bakShopId)
                        ->delete();

        WaiMaiOrderDetailModel::suffix($shopId)
                              ->when($orderId, function ($query) use ($orderId) {
                                  $query->where('orderId', $orderId);
                              })
                              ->when($start, function ($query) use ($start, $end) {
                                  $query->whereBetween('createdAt', [$start, $end]);
                              })
                              ->where('shopId', $bakShopId)
                              ->delete();

        WaiMaiPartRefundLogModel::suffix($shopId)
                              ->when($orderId, function ($query) use ($orderId) {
                                  $query->where('orderId', $orderId);
                              })
                              ->when($start, function ($query) use ($start, $end) {
                                  $query->whereBetween('createdAt', [$start, $end]);
                              })
                              ->where('shopId', $bakShopId)
                              ->delete();

//        WaiMaiOrderModel::suffix($shopId)
//                        ->when($orderId, function ($query) use ($orderId) {
//                            $query->where('orderId', $orderId);
//                        })
//                        ->when($start, function ($query) use ($start, $end) {
//                            $query->whereBetween('createdAt', [$start, $end]);
//                        })
//                        ->where('shopId', $shopId)
//                        ->update(['shopId' => $bakShopId]);
//
//        WaiMaiOrderDetailModel::suffix($shopId)
//                              ->when($orderId, function ($query) use ($orderId) {
//                                  $query->where('orderId', $orderId);
//                              })
//                              ->when($start, function ($query) use ($start, $end) {
//                                  $query->whereBetween('createdAt', [$start, $end]);
//                              })
//                              ->where('shopId', $shopId)
//                              ->update(['shopId' => $bakShopId]);

        // 模拟发送请求
        WaiMaiCallbackLogModel::suffix($shopId)
                              ->where('shopId', $shopId)
                              ->when($orderId, function ($query) use ($orderId) {
                                  $query->where('orderId', $orderId);
                              })
                              ->when($start, function ($query) use ($start, $end) {
                                  $query->whereBetween('createdAt', [$start, $end]);
                              })
                              ->chunk(300, function ($logs) {
                                  $logs->each(function ($item) {

                                      if ($item->sourceType == WaiMaiDBEnum::SOURCE_TYPE_MT_WM) {
                                          if ($item->responseData != '{"data":"ok"}') {
                                              return;
                                          }
                                      }

                                      if ($item->sourceType == WaiMaiDBEnum::SOURCE_TYPE_ELM) {
                                          if ($item->responseData != '{"message":"ok"}') {
                                              return;
                                          }
                                      }

                                      // 调试用
//                                      $this->ask($item->route. '按任意键执行...');

                                      $url      = config('app.url') . $item->route;
                                      $response = (new Client([
                                          'timeout' => 10,
                                          'headers' => [],
                                      ]))->post($url, [RequestOptions::JSON => json_decode($item->requestData, true)]);

                                      $response  = $response->getBody()->getContents();
                                      $createdAt = date('Y-m-d H:i:s', $item->createdAt);
                                      dump(sprintf("%s--%d--%d--%s--%s", $url, $item->orderId, $item->shopId, $response,
                                          $createdAt));
                                  });
                              });

        dump("Data Compare Start......");

        // ****** 数据校验 ******
//        $splits = WaiMaiOrderModel::suffix($shopId)
//                                  ->where('shopId', $shopId)
//                                  ->whereBetween('createdAt', [$start, $end])
//                                  ->get()->keyBy('orderId');
//
//
//        WaiMaiOrderModel::suffix($bakShopId)
//                        ->where('shopId', $bakShopId)
//                        ->whereBetween('createdAt', [$start, $end])
//                        ->get()
//                        ->each(function ($item) use ($splits) {
//                            $splitOrder = $splits[$item->orderId] ?? null;
//                            if (!$splitOrder) {
//                                $this->errs[] = [
//                                    'orderId' => $item->orderId,
//                                    'msg'     => 'split缺少orderId:' . $item->orderId,
//                                ];
//                            }
//
//                            if ($splitOrder->orderStatus == WaiMaiDBEnum::ORDER_STATUS_7) {
//                                return;
//                            }
//
//                            foreach (array_keys($item->toArray()) as $key) {
//                                if (in_array($key, ['acceptAdminName', 'updatedAt'])) {
//                                    continue;
//                                }
//
//                                if ($splitOrder->$key != $item->$key) {
//                                    $this->errs[] = [
//                                        'orderId' => $item->orderId,
//                                        'msg'     => "split {$key}:{$splitOrder->$key} base: {$item->$key}",
//                                    ];
//                                }
//                            }
//                        });
//
//        if ($this->errs) {
//            dump("检查到异常数据，如下：");
//            dump("==============================");
//            dump($this->errs);
//        } else {
//            dump("数据校验 Success √");
//        }

        $delay = time() - $startTime;
        dump("耗时：{$delay}s");
    }
}
